<template>
	<xn-form-container
		:title="formData.id ? '编辑印章管理' : '增加印章管理'"
		:width="500"
		v-model:open="open"
		:destroy-on-close="true"
		@close="onClose"
	>
		<a-form ref="formRef" :model="formData" :rules="formRules" layout="vertical">
			<a-form-item label="机构选择：" name="orgId">
				<a-tree-select
					v-model:value="formData.orgId"
					style="width: 100%"
					:dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
					placeholder="请选择机构"
					allow-clear
					tree-default-expand-all
					:tree-data="treeData"
					:field-names="{
						children: 'children',
						label: 'name',
						value: 'id'
					}"
					selectable="false"
					tree-line
				/>
			</a-form-item>
			<a-form-item label="印章名称：" name="title">
				<a-input v-model:value="formData.title" placeholder="请输入印章名称" allow-clear />
			</a-form-item>
			<a-form-item label="印章类型：" name="type">
				<a-select v-model:value="formData.type" placeholder="请选择印章类型" :options="typeOptions" />
			</a-form-item>
			<a-form-item label="印章图片：" name="sealImg">
				<xn-upload v-model:value="formData.sealImg" uploadMode="image" />
			</a-form-item>
		</a-form>
		<template #footer>
			<a-button style="margin-right: 8px" @click="onClose">关闭</a-button>
			<a-button type="primary" @click="onSubmit" :loading="submitLoading">保存</a-button>
		</template>
	</xn-form-container>
</template>

<script setup name="flwSealForm">
	import tool from '@/utils/tool'
	import { cloneDeep } from 'lodash-es'
	import { required } from '@/utils/formRules'
	import flwSealApi from '@/api/flw/flwSealApi'
	// 抽屉状态
	const open = ref(false)
	const emit = defineEmits({ successful: null })
	const formRef = ref()
	// 表单数据
	const formData = ref({})
	const submitLoading = ref(false)
	const typeOptions = ref([])
	const isDefaultOptions = ref([])
	const treeData = ref([])
	// 打开抽屉
	const onOpen = (record) => {
		open.value = true
		if (record) {
			let recordData = cloneDeep(record)
			formData.value = Object.assign({}, recordData)
		}
		typeOptions.value = tool.dictList('FLW_SEAL_TYPE')
		isDefaultOptions.value = tool.dictList('COMMON_WHETHER')
		// 获取机构树
		flwSealApi.flwSealOrgTreeSelector().then((res) => {
			treeData.value = res
		})
	}
	// 关闭抽屉
	const onClose = () => {
		formRef.value.resetFields()
		formData.value = {}
		open.value = false
	}
	// 默认要校验的
	const formRules = {
		orgId: [required('请选择机构')],
		title: [required('请输入印章名称')],
		type: [required('请选择印章类型')],
		sealImg: [required('请上传印章图片')]
	}
	// 验证并提交数据
	const onSubmit = () => {
		formRef.value.validate().then(() => {
			submitLoading.value = true
			const formDataParam = cloneDeep(formData.value)
			flwSealApi
				.flwSealSubmitForm(formDataParam, formDataParam.id)
				.then(() => {
					onClose()
					emit('successful')
				})
				.finally(() => {
					submitLoading.value = false
				})
		})
	}
	// 抛出函数
	defineExpose({
		onOpen
	})
</script>
